<template>
  <view class="user_login">
    <Head title="用户登陆" :transparent="false">
      <!-- <text slot="action">搜索</text> -->
    </Head>
    <view class="form_label_left">
      <u-form :model="formData" ref="uForm">
        <u-form-item label="手机:" left-icon="phone" prop="account">
          <u-input v-model="formData.account" placeholder="首次登录自动注册" :maxlength="11" />
        </u-form-item>
        <u-form-item label="验证码:" left-icon="chat" prop="code" v-if="loginType === 'captcha'">
          <u-input v-model="formData.code" placeholder="点击右侧按钮获取" />
          <u-verification-code :seconds="seconds" ref="uCode" @change="codeChange" @end="endCount"></u-verification-code>
          <u-button slot="right" :type="countEnd ? 'success' : ''" :disabled="!countEnd" size="mini" @click="getCaptcha">{{tips}}</u-button>
        </u-form-item>
        <u-form-item label="密码:" left-icon="lock" prop="token" v-if="loginType === 'password'">
          <u-input v-model="formData.token" type="password" placeholder="请输入密码" />
        </u-form-item>
        <u-button type="success" class="login_btn" @click="submit">登录</u-button>
      </u-form>
      <view class="text_box">
        <text>您也可以使用</text>
        <text class="text" @click="switchLoginType">{{loginType === 'captcha' ? '账号密码登录' : '短信验证码登录'}}</text>
      </view>
      <!-- <view class="text_box">
        <text>还没有账号？立即</text>
        <text class="text" @click="goRegister">注册</text>
      </view> -->
    </view>
    <view class="one_key_box">
      <!-- 一键登录集合 -->
      <button open-type="getUserInfo" @getuserinfo="wxLogin" class="icon" style="background-image:url(https://xiaoai-1252003722.cos.ap-chengdu.myqcloud.com/wechat.png);"
        plain="true"></button>
      <!-- #ifndef MP-WEIXIN -->
      <button class="icon" style="background-image:url(https://xiaoai-1252003722.cos.ap-chengdu.myqcloud.com/qq.png);"
        plain="true"></button>
      <!-- #endif -->
    </view>
    <view class="agreement_box">
      <text @click="goAgreement">隐私协议</text>
    </view>
  </view>
</template>

<script>
  import Head from '@/pages/pagecomponents/head';
  export default {
    components: {
      Head,
    },
    data() {
      return {
        loginType: "captcha", // 当前选择的登录方式，password账号密码登录，captcha验证码登录
        formData: {
          account: '',
          code: '',
          token: '',
        },
        tips: '获取验证码', // 验证码按钮展示的文案
        seconds: 60, // 验证码倒计时
        countEnd: true, // 倒计时是否结束
        rules: {
          account: [{
            required: true,
            message: '请输入手机号',
            trigger: 'change, blur'
          }, this.$validate.isPhone],
          code: [{
            required: true,
            message: '请输入短信验证码',
            trigger: 'change, blur'
          }],
          token: [{
            required: true,
            message: '请输入密码',
            trigger: 'change, blur'
          }],
        },
        agreementUrl: 'http://www.linyaodao.com:9000/', // 用户协议webview地址
      };
    },
    onLoad() {},
    onReady() {
      this.$refs.uForm.setRules(this.rules); // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
    },
    methods: {
      getCaptcha() {
        // 点击获取验证码
        if(this.$validate.isPhone.pattern.test(this.formData.account)){
          this.$api.user.getLoginCode(this.formData).then(res =>{
            uni.showToast({
              icon: 'none',
              title: '发送成功,请注意查收验证码'
            })
          })
          this.$refs.uCode.start();
          this.countEnd = false; // 倒计时是否结束
        }else{
          uni.showToast({
            icon: 'none',
            title: '请输入正确的手机号'
          })
        }
      },
      endCount() {
        // 倒计时结束，恢复获取验证码按钮
        this.countEnd = true; // 倒计时是否结束
      },
      switchLoginType(){
        // 切换登陆方式
        if(this.loginType === "captcha"){
          this.loginType = 'password'
          this.formData.code = "" // 清空表单
        } else{
          this.loginType = 'captcha'
          this.formData.token = "" // 清空表单
        }
      },
      codeChange(text) {
        // 验证码按钮文案刷新
        this.tips = text;
      },
      submit() {
        this.$refs.uForm.validate(valid => {
          // 点击登录按钮
          if (valid) {
            this.$api.user[this.loginType === 'captcha' ? 'loginByCode' : 'loginByUser'](this.formData)
              .then(res => {
                // 刷新用户信息
                this.$store.state.userInfo = res.data;
                uni.showToast({
                  title: '登录成功'
                });
                setTimeout(() => {
                  let pages = getCurrentPages();
                  if (pages.length > 1) {
                    // 返回上一页
                    uni.navigateBack({
                      delta: 1
                    });
                  } else {
                    uni.redirectTo({
                      url: '/pages/home/index?index=0&ref=index'
                    });
                  }
                }, 2000);
              });
          }
        });
      },
      ttLogin() {
        // 头条一键登陆
        uni.login({
          // provider: 'weixin',
          success: res => {
            console.log(`login调用成功${res.code} ${res.anonymousCode}`);
            let code = res.code; //登录凭证
            let anonymousCode = res.anonymousCode; //登录凭证
            if (code) {
              uni.authorize({
                scope: 'scope.userInfo',
                success: res => {
                  uni.getUserInfo({
                    success: userInfo => {
                      this.$api.user
                        .ttLogin({
                          // 登陆接口
                          ...userInfo,
                          code: code,
                          anonymousCode: anonymousCode
                        })
                        .then(res => {
                          // 调用刷新用户信息方法
                          this.$store.commit('refreshUserInfo');
                          uni.showToast({
                            title: res.data
                          });
                          uni.navigateBack({
                            delta: 1
                          });
                        });
                    },
                    fail: err => {
                      uni.showToast({
                        icon: 'none',
                        title: '获取授权失败'
                      });
                    }
                  });
                },
                fail: res => {
                  uni.openSetting({
                    success: res => {},
                    fail: err => {
                      uni.showToast({
                        icon: 'none',
                        title: '获取授权失败'
                      });
                    }
                  });
                }
              });
            }
          }
        });
      },
      wxLogin(e) {
        if (e.mp.detail.rawData) {
          // 用户成功授权
          uni.login({
            // provider: 'weixin',
            success: res1 => {
              if (res1.code) {
                uni.getUserInfo({
                  success: userInfo => {
                    this.$api.user.wechatLogin({
                      headPortrait: userInfo.userInfo.avatarUrl,
                      nickname: userInfo.userInfo.nickName,
                      code: res1.code,
                    }).then(res2 => {
                      // 调用刷新用户信息方法
                      this.$store.commit('refreshUserInfo');
                      uni.showToast({
                        title: res2.data
                      });
                      uni.navigateBack({
                        delta: 1
                      });
                    });
                  },
                  fail: err => {
                    uni.showToast({
                      icon: 'none',
                      title: err
                    });
                  }
                });
              }
            }
          });
        } else {
          // 用户拒绝授权
          uni.showToast({
            icon: 'none',
            title: '您已拒绝授权，部分功能可能受阻'
          });
        }
      },
      qqLogin(e) {
        uni.login({
          // provider: 'qq',
          success: res => {
            let code = res.code; //登录凭证
            if (code) {
              uni.getUserInfo({
                success: userInfo => {
                  this.$api.user
                    .qqLogin({
                      // 登陆接口
                      ...userInfo,
                      code: code
                    })
                    .then(res => {
                      // 调用刷新用户信息方法
                      this.$store.commit('refreshUserInfo');
                      uni.showToast({
                        title: res.data
                      });
                      uni.navigateBack({
                        delta: 1
                      });
                    });
                },
                fail: err => {
                  uni.showToast({
                    icon: 'none',
                    title: '您已拒绝授权，部分功能可能受阻'
                  });
                }
              });
            }
          }
        });
      },
      goRegister() {
        uni.navigateTo({
          url: '/pages/usercenter/register'
        });
      },
      goAgreement() {
        uni.navigateTo({
          url: `/pages/pagecomponents/webview?src=${this.agreementUrl}`
        });
      },
    }
  };
</script>

<style scoped lang="scss">
  .user_login {
    min-height: 100vh;
    display: flex;
    justify-content: center; // 水平居中
    align-items: center; // 垂直居中

    .form_label_left {
      margin: 0 auto;
      width: 650upx;

      .login_btn {
        margin-top: 20upx;
        width: 100%;
      }

      .text_box {
        margin-top: 20upx;
        color: #888;

        .text {
          margin-left: 5upx;
          color: #1991eb;
        }
      }
    }

    .one_key_box {
      position: fixed;
      bottom: 100upx;
      width: 100%;
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      justify-content: space-around;

      .icon {
        width: 80upx;
        height: 80upx;
        padding: 0;
        background-size: 100%;
        background-repeat: no-repeat;
        border: none;
      }
    }

    .agreement_box {
      text-align: center;
      color: #c8c9cc;
      position: fixed;
      bottom: 50upx;
      width: 100%;
    }
  }
</style>
